package com.charlessong.unionpay.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.charlessong.unionpay.properties.AliPayProperties;
import com.charlessong.unionpay.domain.AjaxResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author charles
 * @Date 2021/11/18
 */
@Slf4j
@AllArgsConstructor
@Service("alipay")
public class AliPayServiceImpl implements IPayService{
    private AliPayProperties aliPayProperties;

    @Override
    public AjaxResult requestPay(String sign) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayProperties.getServerUrl(), aliPayProperties.getAppid(), aliPayProperties.getPrivateKey(), "json", "utf-8", aliPayProperties.getAliPublicKey(), "RSA2");

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        // model.setBody(String.valueOf(System.currentTimeMillis()));
        model.setSubject(String.valueOf(System.currentTimeMillis()));
        model.setOutTradeNo(String.valueOf(System.currentTimeMillis()));
        model.setTimeoutExpress("30m");
        model.setTotalAmount("0.01");

        // model.setProductCode("QUICK_MSECURITY_PAY");

        request.setBizModel(model);
        request.setNotifyUrl(aliPayProperties.getNotifyUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            log.info("========>>>>\n{}\n",response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。

            JSONObject data=new JSONObject();
            data.put("authCode",response.getBody());
            return AjaxResult.success(data);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
